﻿using System;
using System.Diagnostics.Contracts;
using GBricks.Properties;

namespace GBricks
{
  public static class ServiceProviderExtensions
  {
    public static TService GetService<TService>(this IServiceProvider provider) {
      Argument.NotNull(provider, "provider");
      var service = provider.GetService(typeof(TService));
      return service != null ? (TService)service : default(TService);
    }

    public static TService GetRequiredService<TService>(this IServiceProvider provider) {
      Argument.NotNull(provider, "provider");
      return (TService)GetRequiredService(provider, typeof(TService));
    }

    public static object GetRequiredService(this IServiceProvider provider, Type serviceType) {
      Argument.NotNull(provider, "provider");
      Contract.Ensures(Contract.Result<object>() != null);

      var service = provider.GetService(serviceType);
      if(service == null) {
        throw ExceptionBuilder.InvalidOperation(Resources.RequiredServiceNotFound2, serviceType, provider);
      }//if

      return service;
    }
  }
}
